package com.kchouse;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.fm.openinstall.OpenInstall;
import com.fm.openinstall.listener.AppWakeUpAdapter;
import com.fm.openinstall.model.AppData;
import com.kchouse.common.BaseActivity;
import com.kchouse.common.SharedPreferencesUtil;
import com.kchouse.common.ToastUtils;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.UpgradeInfo;

import android.Manifest;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


public class MainActivity extends BaseActivity {


    private MainActivity mContext;
    private static FragmentTabHost mTabHost;

    public static String token;
    public static String userid;
    public static String mobile;
    public static String userName;
    private Intent intent=new Intent();


    private Class[] fragment = new Class[]{
            HomepageFragment.class,
//            InquiryFragment.class,
            UnionFragment.class,
//            SecCarFragment.class,
            MineFragment.class,
    };

    private String[] tabname = new String[]{
            "首页",  "联盟",  "我的"};
//            "首页", "询价", "联盟", "二手车", "我的"};


    private int[] mTabIconRes = new int[]{
            R.drawable.ic_tab_homepage,
//            R.drawable.ic_tab_community,
            R.drawable.ic_tab_union,
//            R.drawable.ic_tab_seccar,
            R.drawable.ic_tab_mine,
    };
    private long exitTime;


    AppWakeUpAdapter wakeUpAdapter = new AppWakeUpAdapter() {
        @Override
        public void onWakeUp(AppData appData) {
            //获取渠道数据
//            String channelCode = appData.getChannel();
//            //获取绑定数据
//            String bindData = appData.getData();
//            Log.d("OpenInstall", "getWakeUp : wakeupData = " + appData.toString());

            Log.e("获取渠道数据",appData.toString());
            ToastUtils.getInstanc(MainActivity.this).showToast(appData.toString());
        }
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        intiData();
        initView();

        //获取唤醒参数
        OpenInstall.getWakeUp(getIntent(), wakeUpAdapter);



    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 此处要调用，否则App在后台运行时，会无法截获
        OpenInstall.getWakeUp(intent, wakeUpAdapter);
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        wakeUpAdapter = null;
    }



    private void intiData() {


    }


    private void initView() {
        inittabhost();
    }


    @Override
    protected void onResume() {
        super.onResume();
//
//        if (!isLocationEnabled()) {
//            ToastUtils.getInstanc(mContext).showToast("请尚未开启手机定位功能");
//        }
        loadUpgradeInfo();

        token = (String) SharedPreferencesUtil.getParam(mContext, "token", "");
        mobile = (String) SharedPreferencesUtil.getParam(mContext, "mobile", "");
        userid = (String) SharedPreferencesUtil.getParam(mContext, "userid", "");
        userName = (String) SharedPreferencesUtil.getParam(mContext, "userName", "");
    }

    private void loadUpgradeInfo() {

        /***** 获取升级信息 *****/
        UpgradeInfo upgradeInfo = Beta.getUpgradeInfo();

        if (upgradeInfo == null) {
//            tvUpgradeInfo.setText("无升级信息");
//            Toast.makeText(mContext,"无升级信息",Toast.LENGTH_LONG).show();
            Log.e("loadUpgradeInfo", "无升级信息");
            return;
        }

        StringBuilder info = new StringBuilder();
        info.append("id: ").append(upgradeInfo.id).append("\n");
        info.append("标题: ").append(upgradeInfo.title).append("\n");
        info.append("升级说明: ").append(upgradeInfo.newFeature).append("\n");
        info.append("versionCode: ").append(upgradeInfo.versionCode).append("\n");
        info.append("versionName: ").append(upgradeInfo.versionName).append("\n");
        info.append("发布时间: ").append(upgradeInfo.publishTime).append("\n");
        info.append("安装包Md5: ").append(upgradeInfo.apkMd5).append("\n");
        info.append("安装包下载地址: ").append(upgradeInfo.apkUrl).append("\n");
        info.append("安装包大小: ").append(upgradeInfo.fileSize).append("\n");
        info.append("弹窗间隔（ms）: ").append(upgradeInfo.popInterval).append("\n");
        info.append("弹窗次数: ").append(upgradeInfo.popTimes).append("\n");
        info.append("发布类型（0:测试 1:正式）: ").append(upgradeInfo.publishType).append("\n");
        info.append("弹窗类型（1:建议 2:强制 3:手工）: ").append(upgradeInfo.upgradeType);
        Toast.makeText(mContext, info, Toast.LENGTH_LONG).show();
//        tvUpgradeInfo.setText(info);
        Log.e("loadUpgradeInfo", info.toString());
    }


    private void inittabhost() {
        // 实例化tabhost
        mTabHost = (FragmentTabHost) findViewById(R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(),
                R.id.realtabcontent);

        for (int i = 0; i < fragment.length; i++) {
            TabHost.TabSpec spec = mTabHost.newTabSpec(tabname[i]).setIndicator(getView(i));
            mTabHost.addTab(spec, fragment[i], null);

        }

        mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {

                switch (tabId)
                {
//                    case "首页":
//                        intent.setAction("refresh");
//                        //发送广播
//                        sendBroadcast(intent);
//                        break;
                    case "联盟":
                        //TODO  暂时没办法实时更新
//                        intent.setAction("MerchantList");
//                        //发送广播
//                        sendBroadcast(intent);
//                        UnionFragment unionFragment = (UnionFragment) getFragment(tabId);
//                        unionFragment.getefreshFrament();
                        break;
                }
            }
        });
    }

    private Fragment getFragment(String tabId)
    {
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        for(Fragment fragment : fragments) {
            String str1 = fragment.getTag();
            String str2 = String.valueOf(tabId);
            if(str1 != null && str1.equals(str2)) // 最开始没有检查str1是否为空，导致crash！
                return fragment;
        }
        return null;
    }

    private View getView(int i) {
        //取得布局实例
        View view = View.inflate(mContext, R.layout.tab_item, null);
        //取得布局对象
        ImageView imageView = (ImageView) view.findViewById(R.id.headline_iv);
        TextView textView = (TextView) view.findViewById(R.id.headline_tv);

        //设置图标
        imageView.setImageResource(mTabIconRes[i]);
        //设置标题
        textView.setText(tabname[i]);
        return view;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {

            if ((System.currentTimeMillis() - exitTime) > 2000)  //System.currentTimeMillis()无论何时调用，肯定大于2000
            {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction("LoginAction");
        //注册广播
        registerReceiver(new MyReceiver(), myIntentFilter);
    }

    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            token = (String) SharedPreferencesUtil.getParam(mContext, "token", "");
            mobile = (String) SharedPreferencesUtil.getParam(mContext, "mobile", "");
            userid = (String) SharedPreferencesUtil.getParam(mContext, "userid", "");
        }
    }
}
